"""doc"""
import logging
import json
from datetime import timedelta

from django.core.cache import cache
from django.conf import settings
from django.views import View
from django.http import HttpRequest
from django.db import transaction
from django.utils.decorators import method_decorator
from django.utils import timezone
from django.contrib.auth.base_user import AbstractBaseUser

from rest_framework.parsers import JSONParser

from app_common import (
    app_page,
    app_except,
    app_str_check,
    app_uuid,
    json_response_utf8_ok,
)

from . import models, ser, wx_api, wx_pay, access_auth

logger = logging.getLogger("log")


# wx api
@method_decorator(access_auth.all_user_access, name="get")
@method_decorator(access_auth.owner_access, name="post")
@method_decorator(access_auth.owner_access, name="put")
@method_decorator(access_auth.owner_access, name="delete")
class StoreGoodTypeView(View):
    """doc"""

    def get(self, request: HttpRequest, *args, **kwargs):
        """查询所有的商品类型"""
        objs = models.StoreGoodType.objects.filter(deleted=False)
        _objs, num_pages = app_page.page(request, objs)
        m_s = ser.StoreGoodTypeSer(_objs, many=True)
        return json_response_utf8_ok({"data": m_s.data, "num_pages": num_pages})

    @transaction.atomic
    def post(self, request: HttpRequest, *args, **kwargs):
        """doc"""
        body: dict = JSONParser().parse(request)
        now = timezone.now()
        _bulk_create = []

        for _info in body["list"]:
            _info = dict(_info)
            _info["created_at"] = now

            # check attrs is exists
            _ = _info["name"]
            _ = _info["weight"]

            _bulk_create.append(models.StoreGoodType(**_info))

        # this objs return by bulk_create does not have uuid ... fields which created auto
        incomplete_objs = models.StoreGoodType.objects.bulk_create(_bulk_create)

        objs = models.StoreGoodType.objects.filter(deleted=False).filter(created_at=now)
        _objs, num_pages = app_page.page(request, objs)
        m_s = ser.StoreGoodTypeSer(_objs, many=True)
        return json_response_utf8_ok({"data": m_s.data, "num_pages": num_pages})

    @transaction.atomic
    def put(self, request: HttpRequest, *args, **kwargs):
        """"""
        body: dict = JSONParser().parse(request)
        uuids = []

        for _info in body["list"]:
            _info = dict(_info)
            _uuid = _info.pop("uuid")
            uuids.append(_uuid)

            obj = (
                models.StoreGoodType.objects.filter(deleted=False)
                .filter(uuid=_uuid)
                .select_for_update()
                .first()
            )
            if not obj:
                raise app_except.ObjNotExist(msg=f"商品不存在: {_uuid}")

            obj_s = ser.StoreGoodTypeSer(obj, data=_info, partial=True)
            obj_s.is_valid(raise_exception=True)
            obj_s.save()

        objs = models.StoreGoodType.objects.filter(deleted=False).filter(uuid__in=uuids)
        _objs, num_pages = app_page.page(request, objs)
        m_s = ser.StoreGoodTypeSer(_objs, many=True)
        return json_response_utf8_ok({"data": m_s.data, "num_pages": num_pages})

    @transaction.atomic
    def delete(self, request, *args, **kwargs):
        body: dict = JSONParser().parse(request)
        uuids = body["list"]
        n = (
            models.StoreGoodType.objects.filter(deleted=False)
            .filter(uuid__in=uuids)
            .update(deleted=True, del_race=timezone.now())
        )
        if 0 == n:
            raise app_except.ObjNotExist(msg=f"{uuids}")
        return json_response_utf8_ok({"data": n})
